package com.leyou.user.web;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.interceptors.LoginInterceptor;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author YYP
 * @date 2021/1/9
 */
@RestController
@RequestMapping("/info")
public class UserController {
    @Autowired
    private UserService userService;

    /*注册用户*/
    @PostMapping
    public ResponseEntity<Void> RegisterUser(
            @Valid User user,
            @RequestParam("code") String code) {
        userService.registerUser(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名密码查询
     * @param username
     * @param password
     * @return
     */
    @GetMapping
    public ResponseEntity<UserDTO> QueryUser(@RequestParam("username") String username, @RequestParam("password") String password) {

        return ResponseEntity.ok(userService.queryUser(username, password));
    }


    /**
     * 检查用户输入的用户名或手机号是否唯一
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> isExistsData(
            @PathVariable("data") String data,
            @PathVariable("type") Integer type
    ) {
        return ResponseEntity.ok(userService.isExistsData(data, type));
    }

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone){
        userService.sendVerifyCode(phone);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

   /* @GetMapping("/me")
    public ResponseEntity<UserDetail> showUser(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
           if ((JwtConstants.COOKIE_NAME).equals(cookie.getName())){
               String token = cookie.getValue();
           }
        }
    }*/
    /**
     * 校验token，返回UserDetail
     *
     * @return
     */
    @GetMapping("/me")
    public ResponseEntity<UserDetail> showUser(){
   // public ResponseEntity<UserDetail> showUser(@CookieValue("LY_TOKEN")String token){
//        return ResponseEntity.ok(this.userService.showUser(token));
        return ResponseEntity.ok(LoginInterceptor.getUser());
    }


}
